<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-if="BUTTONS.add" type="primary" :icon="CirclePlus" @click="openDialog('新增')"> 新增 </el-button>
        <el-button v-if="BUTTONS.import" type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button v-if="BUTTONS.export" type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDialog('查看', scope.row)">查看</el-button>
        <el-button type="primary" v-if="BUTTONS.edit" link :icon="EditPen" @click="openDialog('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="CopyDocument" @click="copyUserRequirement(scope.row)">复制</el-button>
        <el-button type="primary" v-if="BUTTONS.delete" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <UserRequirementDialog ref="dialogRef" />
    <ImportExcel ref="excelRef" />
  </div>
</template>

<script setup lang="tsx" name="userRequirement">
import { ref, reactive, computed, onMounted } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserRequirementDialog from "./userRequirementDialog.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Download, Upload, CopyDocument } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { dateRender, productRender, userRender } from "@/hooks/useColumnRender";
import { useDataStore } from "@/stores/modules/data";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox, ElMessage } from "element-plus";
import { useDateFormat } from "@vueuse/core";
import { ExportColType } from "@/enums/sysEnum";
import { UserRequirement } from "./types/userRequirement";
import { useUserStore } from "@/stores/modules/user";

const dataStore = useDataStore();
const { BUTTONS } = useAuthButtons();
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

const initVar = reactive({
  tbName: "user_requirement"
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

const productList = computed(() => dataStore.productList);
const userList = computed(() => dataStore.userList);
const reqTypeList = computed(() => dataStore.getEnumByCsName("REQ_TYPE"));
const reqStateList = computed(() => dataStore.getEnumByCsName("REQ_STATE"));
const sprintList = computed(() => dataStore.getDataByKey("sprint_id_name"));
const itemList = computed(() => dataStore.getDataByKey("item_id_name"));

onMounted(() => {
  dataStore.findProductList();
  dataStore.findUserList();
  dataStore.findEnumByCsName("REQ_TYPE");
  dataStore.findEnumByCsName("REQ_STATE");
  dataStore.findList("sprint_id_name", () => apiService.find("sprint", {}, { fields: ["_id", "name"] }));
  dataStore.findList("item_id_name", () => apiService.find("item", {}, { fields: ["_id", "name"] }));
});

// 表格配置项
const columns = reactive<ColumnProps<UserRequirement>[]>([
  { type: "index", label: "序号", width: 65 },
  { prop: "summary", align: "left", label: "需求摘要", search: { el: "input", like: true }, width: 200 },
  {
    prop: "type",
    label: "需求类型",
    width: 90,
    enum: reqTypeList,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "itemId",
    label: "项目",
    width: 140,
    render: scope => productRender(scope, itemList)
  },
  { prop: "jt_no", label: "JT单号", search: { el: "input", like: true }, width: 120 },
  {
    prop: "jt_date",
    label: "JT提单日期",
    width: 120,
    render: dateRender
  },

  {
    prop: "state",
    label: "状态",
    width: 90,
    enum: reqStateList,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "important", label: "重要性", width: 90 },
  { prop: "productId", label: "所属产品", width: 140, render: scope => productRender(scope, productList) },
  { prop: "front_workload", label: "前端", width: 80 },
  { prop: "back_workload", label: "后端", width: 80 },
  { prop: "po", label: "产品负责人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "item_verifier", label: "项目对接人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "customer_verifier", label: "客户验证人", width: 100, render: scope => userRender(scope, userList) },
  {
    prop: "sprintId",
    label: "冲刺",
    width: 140,
    render: scope => productRender(scope, sprintList)
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
]);

const getExcelConfig = (): any => {
  return {
    params: proTable.value?.searchParam,
    tableName: initVar.tbName,
    keyPropName: "id",
    enumTypes: ["REQ_TYPE", "REQ_STATE"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "product", fields: ["_id", "name"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "需求摘要", width: 30, ext: { prop: "summary", type: ExportColType.DEFAULT } },
      { header: "JT编号", width: 15, ext: { prop: "jt_no", type: ExportColType.DEFAULT } },
      { header: "JT提单日期", width: 12, ext: { prop: "jt_date", type: ExportColType.DATE } },
      { header: "需求类型", width: 10, ext: { prop: "type", type: ExportColType.ENUM, key: "REQ_TYPE" } },
      { header: "状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "REQ_STATE" } },
      { header: "重要性", width: 10, ext: { prop: "important", type: ExportColType.DEFAULT } },
      { header: "所属产品", width: 15, ext: { prop: "productId", type: ExportColType.TABLE, key: "product" } },
      { header: "前端工作量", width: 10, ext: { prop: "front_workload", type: ExportColType.DEFAULT } },
      { header: "后端工作量", width: 10, ext: { prop: "back_workload", type: ExportColType.DEFAULT } },
      {
        header: "产品负责人",
        width: 12,
        ext: { prop: "po", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "项目对接人",
        width: 12,
        ext: { prop: "item_verifier", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "客户验证人",
        width: 12,
        ext: { prop: "customer_verifier", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "冲刺ID", width: 15, ext: { prop: "sprintId", type: ExportColType.DEFAULT } },
      {
        header: "创建人",
        width: 12,
        ext: { prop: "create_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 12, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(
      apiService.commonExport,
      `用户需求清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`,
      "",
      getExcelConfig(),
      false
    )
  );
};

// 导入数据
const excelRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "用户需求",
    defaultTip: "需求ID相同则跳过",
    coverTip: "需求ID相同则覆盖",
    tempUrl: "/template/userRequirement",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  excelRef.value?.acceptParams(params);
};

// 删除用户信息
const deleteAccount = async (params: UserRequirement) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params.id, `删除需求【${params.summary}】`);
  proTable.value?.getTableList();
};

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref<InstanceType<typeof UserRequirementDialog> | null>(null);
const openDialog = (title: string, row: Partial<UserRequirement> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: { ...row },
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

// 复制用户需求
const copyUserRequirement = async (row: UserRequirement) => {
  try {
    // 创建一个新的用户需求对象，排除id属性
    const newUserRequirement = { ...row };
    delete (newUserRequirement as any)._id;

    // 重新设置创建人和创建时间
    newUserRequirement.create_at = new Date(); // 设置新的创建时间
    newUserRequirement.create_user = useUserStore().userInfo._id!; // 让后端重新设置创建人

    // 在需求摘要前添加[复制]标记
    if (newUserRequirement.summary && !newUserRequirement.summary.startsWith("[复制]")) {
      newUserRequirement.summary = `[复制]${newUserRequirement.summary}`;
    }

    // 保存新的用户需求数据
    await apiService.save(initVar.tbName, newUserRequirement);

    // 刷新表格
    proTable.value?.getTableList();

    ElMessage.success("用户需求复制成功");
  } catch (error) {
    console.error("复制用户需求失败:", error);
    ElMessage.error("用户需求复制失败");
  }
};
</script>
